package com.yeskery.nut.http.controller;

import com.yeskery.nut.core.*;
import com.yeskery.nut.util.StringUtils;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 默认的异常Controller
 * @author sprout
 * 2022-05-18 10:44
 */
public class DefaultErrorController extends DefaultController {

    /** Accept 请求头分隔符 */
    private static final String ACCEPT_SEPARATOR = ",";

    /** 响应编码 */
    private final ResponseCode responseCode;

    /**
     * 构造一个默认的异常Controller
     * @param responseCode 响应编码
     */
    public DefaultErrorController(ResponseCode responseCode) {
        super(responseCode.getCode(), responseCode.getDescription());
        this.responseCode = responseCode;
    }

    @Override
    public void doGet(Request request, Response response, Execution execution) {
        String accept = request.getHeader(HttpHeader.ACCEPT);
        if (StringUtils.isEmpty(accept)) {
            super.doGet(request, response, execution);
        } else {
            for (String acceptType : accept.split(ACCEPT_SEPARATOR)) {
                acceptType = acceptType.trim();
                if (MediaType.APPLICATION_JSON.getValue().equals(acceptType)) {
                    writeJsonError(request, response);
                    return;
                } else if (MediaType.TEXT_XML.getValue().equals(acceptType)
                        || MediaType.APPLICATION_XML.getValue().equals(acceptType)) {
                    writeXmlError(request, response);
                    return;
                }
            }
            super.doGet(request, response, execution);
        }
    }

    /**
     * 处理json错误
     * @param request 请求
     * @param response 响应
     */
    private void writeJsonError(Request request, Response response) {
        String body = "{\"timestamp\": \"" + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now())
                + "\",\n  \"status\": " + responseCode.getCode() + ",\n  \"message\": \""
                + responseCode.getDescription() + "\",\n  \"path\": \"" + request.getPath() + "\"\n}";
        response.writeJson(body);
    }

    /**
     * 处理json错误
     * @param request 请求
     * @param response 响应
     */
    private void writeXmlError(Request request, Response response) {
        String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Result>\n  <Timestamp>"
                + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()) + "</Timestamp>\n  <Status>"
                + responseCode.getCode() + "</Status>\n  <Message>" + responseCode.getDescription()
                + "</Message>\n  <Path>" + request.getPath() + "</Path>\n</Result>";
        response.write(body, MediaType.TEXT_XML);
    }
}
